import os
import sys
import json
import django
import datetime

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
print(BASE_DIR)
sys.path.extend([BASE_DIR, ])
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "finance_c2c.settings")

django.setup()
from apps.coffee.models import CouponInfo
from core.wchat.mini_base import wechat_client, wechat_client_howhow
from django.contrib.auth import get_user_model
from django.db.models import Q

UserModel = get_user_model()


def coupon_message_notice():
    now_time = datetime.date.today()
    end_time_3 = now_time + datetime.timedelta(days=3)
    end_time_7 = now_time + datetime.timedelta(days=7)
    # 券过期
    base_queryset = CouponInfo.objects.filter(expired=False, used=False, c_type__in=CouponInfo.show_c_type_list)
    base_queryset = base_queryset.filter(Q(expire_time=end_time_3) | Q(expire_time=end_time_7))
    # queryset = base_queryset.values("user", "expire_time").annotate(counts=Count("id")).order_by("expire_time")
    queryset = base_queryset.values_list("user", flat=True).distinct()
    message_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    for i in queryset:
        coupon_info = base_queryset.filter(user_id=i).order_by("expire_time")[0]
        expire_time = coupon_info.expire_time.strftime("%Y-%m-%d")
        name = coupon_info.name
        print(coupon_info.user_id, coupon_info.id)
        message = "优惠券即将到期，请尽快使用"

        data = {
            "thing1": {
                "value": name
            },
            "time2": {
                "value": expire_time
            },
            "thing5": {
                "value": message
            },
            "time8": {
                "value": message_time
            },
        }
        user = UserModel.objects.get(id=i)
        if user.wx_mini_user:
            openid = user.wx_mini_user.openid
            template_id = "CJhPG7J0JVOz6KKwy2w4Icx7p9wHZtZ__cVIDcUo0Pg"
            try:
                # openid = "oKtsR5Y63MhZ8Jp1oYiABJ3i8dJs"
                response = wechat_client.wechat_extra.mini_send_subscribe_template(openid, template_id, data,
                                                                                   "pages/coupon/coupon",
                                                                                   miniprogram_state="formal")
                print("response", response, user.mobile, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
            except Exception as e:
                print(e, user.id, user.mobile, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))


def coupon_message_notice_howho():
    now_time = datetime.date.today()
    end_time_3 = now_time + datetime.timedelta(days=3)
    end_time_7 = now_time + datetime.timedelta(days=7)
    # 券过期
    base_queryset = CouponInfo.objects.filter(expired=False, used=False, c_type__in=CouponInfo.show_c_type_list)
    base_queryset = base_queryset.filter(Q(expire_time=end_time_3) | Q(expire_time=end_time_7))
    # queryset = base_queryset.values("user", "expire_time").annotate(counts=Count("id")).order_by("expire_time")
    queryset = base_queryset.values_list("user", flat=True).distinct()
    message_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    for i in queryset:
        coupon_info = base_queryset.filter(user_id=i).order_by("expire_time")[0]
        expire_time = coupon_info.expire_time.strftime("%Y-%m-%d")
        name = coupon_info.name
        print(coupon_info.user_id, coupon_info.id)
        message = "优惠券即将到期，请尽快使用"

        data = {
            "thing1": {
                "value": name
            },
            "time2": {
                "value": expire_time
            },
            "thing5": {
                "value": message
            },
            "time8": {
                "value": message_time
            },
        }
        user = UserModel.objects.get(id=i)
        if user.wx_mini_user:
            openid = user.wx_mini_user.openid
            template_id = "OTgT7v9BIKXbRdyE2hBitxHIbU06ZY2q4nBqTWCf3QY"
            try:
                # openid = "oKtsR5Y63MhZ8Jp1oYiABJ3i8dJs"
                response = wechat_client_howhow.wechat_extra.mini_send_subscribe_template(openid, template_id, data,
                                                                                   "pages/coupon/coupon",
                                                                                   miniprogram_state="formal")
                print("response", response)
            except Exception as e:
                print(e, user.id)


if __name__ == '__main__':
    coupon_message_notice()
